/*
 * Copyleft 2012 Power by Colen.
 *
 * Project: app-crm
 * Date: Apr 22, 2012
 */
package com.crm.common.context;

import java.util.Map;

import javax.servlet.ServletContext;

import org.springframework.web.context.WebApplicationContext;

import com.crm.common.exception.CrmSysException;

/**
 * Web Application Context Holder
 *
 * @author Colen
 *
 */
public final class AppContextHolder {


    /**
     * Constructor
     *
     */
    private AppContextHolder() {}

    /** AppContextHolder */
    private static AppContextHolder instance = null;


    /**
     * Get Instance.
     *
     * @return instance.
     */
    public synchronized static AppContextHolder getInstance() {
        if (instance == null) {
            instance = new AppContextHolder();
        }
        return instance;
    }


    /**
     * Initialize
     *
     * @param context WebApplicationContext.
     */
    public synchronized void init(WebApplicationContext context) {
        if (this.initialized) {
            throw new CrmSysException("App Context Holder has alreadly Initialized!");
        }
        this.wac = context;
        this.sc = context.getServletContext();
        this.initialized = true;
    }


    /**
     * Get Bean
     *
     * @param id ID.
     * @return Object.
     */
    public static Object getBean(String id) {
        return instance.wac.getBean(id);
    }

    /**
     * Get Beans of type
     *
     * @param calss
     * @return
     */
    public static <T> Map<String, T> getBeansOfType(Class<T> calss) {
        return instance.wac.getBeansOfType(calss);
    }


    /**
     * get real path
     *
     * @param path path
     * @return
     */
    public static String getRealPath(String path) {
        return instance.sc.getRealPath(path);
    }
    

    /** initialized flag */
    private boolean initialized = false;

    /** Servlet Context */
    private ServletContext sc = null;
    /** WebApplicationContext */
    private WebApplicationContext wac = null;
}
